package com.jade.bss.ec.ware.impl;

import java.util.List;

import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.bss.ec.ware.WareException;
import com.jade.bss.ec.ware.WareImage;
import com.jade.bss.ec.ware.WareImageDao;
import com.jade.bss.ec.ware.WareImageManager;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Order;
import com.jade.framework.base.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品图片管理器实现。
 */
@Named ("bss_wareImageManager")
public class ImageManagerImpl
        implements WareImageManager
{
    private WareImageDao imageDao;

    @Inject
    public void setImageDao(@Named ("bss_wareImageDao") WareImageDao imageDao)
    {
        this.imageDao = imageDao;
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Throwable.class)
    public void addImage(WareImage image)
            throws WareException
    {
        imageDao.addImage(image);
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Throwable.class)
    public void removeImage(long... ids)
            throws WareException
    {
        for (long id : ids) {
            WareImage image = getImage(id);
            if (image != null) {
                imageDao.removeImage(image);
                //todo 删除实际文件
            }
        }
    }

    public WareImage getImage(long id)
    {
        return imageDao.getImage(id);
    }

    public WareImage getMainImage(long wareId)
    {
        Criteria criteria = new Criteria(0, 1);
        criteria.add(Restrictions.eq("mainImage", true));
        List<WareImage> images = imageDao.listImage(wareId, criteria);
        return images.isEmpty() ? null : images.get(0);
    }

    public List<WareImage> listImage(long wareId, long colorSpec)
    {
        Criteria criteria = new Criteria(0, 1);
        criteria.add(Restrictions.eq("colorSpec", colorSpec));
        criteria.addOrder(Order.asc("id"));
        return imageDao.listImage(wareId, criteria);
    }
}
